package microcloud.keien.myofo;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.TimeUnit;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by c1720 on 2017/1/17.
 */

public class PublishPopWindow extends PopupWindow implements View.OnClickListener {
    private View rootView;
    private Activity mActivity;
    private RelativeLayout contentView;
    private EditText mEditTextshulu;
    private EditText mEditTextmima;
    private TextInputLayout mInshulu;
    private TextInputLayout mInmima;
    private Button mButton;

    public PublishPopWindow(Activity activity) {
        this.mActivity = activity;
    }

    public void showMoreWindow(View anchor) {
        LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(R.layout.popu_dialog, null);

        int h = mActivity.getWindowManager().getDefaultDisplay().getHeight();
        int w = mActivity.getWindowManager().getDefaultDisplay().getWidth();
        setContentView(rootView);
        this.setWidth(w);
        this.setHeight(h - ScreenUtils.getStatusHeight(mActivity));

        contentView = (RelativeLayout) rootView.findViewById(R.id.contentView);
        LinearLayout close = (LinearLayout) rootView.findViewById(R.id.ll_close);
        mButton = (Button) rootView.findViewById(R.id.bu_jia);
        mEditTextshulu = (EditText) rootView.findViewById(R.id.edi_number_shulu);
        mEditTextmima = (EditText) rootView.findViewById(R.id.edi_mima);
        mInshulu = (TextInputLayout)rootView.findViewById(R.id.in_shulu);
        mInmima = (TextInputLayout)rootView.findViewById(R.id.in_mima);

        mEditTextshulu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (mEditTextshulu.equals("")||mEditTextmima.equals("")){
                    mButton.setClickable(false);
                    mButton.setTextColor(mActivity.getColor(R.color.colorGraty));
                }else {
                    mButton.setClickable(true);
                    mButton.setTextColor(mActivity.getColor(R.color.colorBlack));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mInshulu.getError()!=null){
                    mInshulu.setError(null);
                }
            }
        });
        mEditTextmima.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (mEditTextshulu.equals("")||mEditTextmima.equals("")){
                    mButton.setClickable(false);
                    mButton.setTextColor(mActivity.getColor(R.color.colorGraty));
                }else {
                    mButton.setClickable(true);
                    mButton.setTextColor(mActivity.getColor(R.color.colorBlack));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mInmima.getError()!=null){
                    mInmima.setError(null);
                }
            }
        });
        mEditTextmima.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE){
                    //TODO 还是隐藏不了虚拟键盘
                    InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(mActivity.getWindow().getDecorView().getWindowToken(),InputMethodManager.RESULT_UNCHANGED_HIDDEN);
                    bujia();
                    return true;
                }
                return false;
            }
        });
        mButton.setOnClickListener(this);
        close.setBackgroundColor(0xFFFFFFFF);
        close.setOnClickListener(this);
        showAnimation(contentView);
        setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.translucence_with_white));
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 显示进入动画效果
     *
     * @param layout
     */

    private void showAnimation(ViewGroup layout) {
        //遍历根试图下的一级子试图
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            //忽略关闭组件
            if (child.getId() == R.id.ll_close) {
                continue;
            }
            //设置所有一级子试图的点击事件
            child.setOnClickListener(this);
            child.setVisibility(View.INVISIBLE);
            //延迟显示每个子试图(主要动画就体现在这里)
            Observable.timer(i * 50, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            child.setVisibility(View.VISIBLE);
                            ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 600, 0);
                            fadeAnim.setDuration(300);
                            KickBackAnimator kickAnimator = new KickBackAnimator();
                            kickAnimator.setDuration(150);
                            fadeAnim.setEvaluator(kickAnimator);
                            fadeAnim.start();
                        }
                    });
        }
    }

    /**
     * 关闭动画效果
     *
     * @param layout
     */
    private void closeAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.ll_close) {
                continue;
            }
            Observable.timer((layout.getChildCount() - i - 1) * 30, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            child.setVisibility(View.VISIBLE);
                            ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 0, 600);
                            fadeAnim.setDuration(200);
                            KickBackAnimator kickAnimator = new KickBackAnimator();
                            kickAnimator.setDuration(100);
                            fadeAnim.setEvaluator(kickAnimator);
                            fadeAnim.start();
                            fadeAnim.addListener(new Animator.AnimatorListener() {

                                @Override
                                public void onAnimationStart(Animator animation) {
                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {
                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    child.setVisibility(View.INVISIBLE);
                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {
                                }
                            });
                        }
                    });
            if (child.getId() == R.id.ll_cont) {
                Observable.timer((layout.getChildCount() - i) * 30 + 80, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Long>() {
                            @Override
                            public void call(Long aLong) {
                                dismiss();
                            }
                        });
            }

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bu_jia:
                bujia();
                break;
            case R.id.ll_close:
                if (isShowing()) {
                    closeAnimation(contentView);
                }
                break;
            default:
                break;
        }
    }

    private void bujia(){
        String shulu = mEditTextshulu.getText().toString();
        String mima = mEditTextmima.getText().toString();
        if (panduan(shulu,mima)){
            jia(shulu,mima);
        }
    }

    private boolean panduan(String shulu,String mima) {
        if (TextUtils.isEmpty(shulu)||!isShuluValid(shulu)){
            mInshulu.setError("请输入正确的车牌号");
            return false;
        }
        if (TextUtils.isEmpty(mima)||!isMimaValid(mima)){
            mInmima.setError("请输入正确的密码");
            return false;
        }
        return true;
    }

    private boolean isShuluValid(String shulu){
        return shulu.length()>3;
    }

    private boolean isMimaValid(String mima){
        return mima.length()==4;
    }

    private void jia(String shulu,String mima) {
        CheModel model = new CheModel(shulu,mima);
        model.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Toast.makeText(mActivity,"添加成功"+"返回objectId为"+s,Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(mActivity,"添加失败"+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
